import { makeAutoObservable, action, reaction, configure, observable } from 'mobx';
import { useWebSocket } from '~/common';
import { debounce } from 'lodash';
import deviceStore from './deviceStore';

configure({
    enforceActions: "never",
})
interface SleepInfo {
    br_value: number,
    cmd: string,
    hr_value: number,
    s_status: number,
    array_data: Array<[]>
}

interface InComingCall {
    agora: {
        app_id: string;
        channel_id: string;
        token: string;
        user_id: number
    };
    call_data: {
        call_id: string;
        call_type: string;
        call_way: string
    };
    user: {
        avatar_url: string;
        device_sn: string;
        guardian_cnt: string;
        mobile: string;
        name: string;
        user_id: string
    }
    call_id: string;
    cmd: string;
}

class WebSocketStore {
    sleep = {} as SleepInfo;
    isConnected = false; // WebSocket 连接状态
    messages: any = null; // 临时存储 WebSocket 返回的消息
    device_online = 0; // 设备在线状态
    firmware_version = ''; // 设备版本
    progress = 0; // 进度
    volume = 0;// 音量
    callRoleStatus = 0; // 1、监护人 2、数据大屏｜管家
    coInterval = 0; // 烟雾报警
    typeDeviceConnect = -1; // -1 0、无设备 1、睡眠袋 2、按键面板 3、手指夹
    fingerInfo = { data: [], sample_finish: 0 }; // 手指夹实时测量
    linkSubDeviceStatus = 0; // 子设备连接状态
    linkSubDeviceSn = '';// 连接成功的设备编号
    inComingCall = {} as InComingCall; // 来电通知
    inComingVisible = false;
    isHandlingCall = false;
    deviceList: any = observable.array([]); // 用来存储设备列表
    bleRssiMap = new Map()
    subDevices: any = [] // 获取的子设备
    constructor() {
        makeAutoObservable(this);

        reaction(
            () => this.linkSubDeviceStatus, // Watch for linkSubDeviceStatus changes
            (newStatus) => {
                if (newStatus !== null) {
                }
            }
        );

        reaction(
            () => this.messages,
            debounce((newMessages) => {
                this.handleMessages(newMessages);
            }, 300) // 防抖延迟 300 毫秒
        );
    }
    @action.bound
    // 更新设备状态的函数
    updateDeviceStatus(sn_id, status) {
        const device: any = this.deviceList.find((item: any) => item.armarium_device_chang === sn_id);
        if (device) {
            device.status = status;
        }
    }
    // 添加对应的子设备
    singSubDevices(arr) {
        this.subDevices = arr.map(item => {
            const rssiData = this.bleRssiMap.get(item.device_sn);
            return {
                ...item,
                device_rssi: rssiData ? rssiData.rssi : item.device_rssi ?? null,
            };
        });
    }
    // 删除对应的子设备
    removeDevice(sn: string) {
        this.subDevices = this.subDevices.filter(d => d.device_sn !== sn);
    }
    singDevices(arr) {
        this.deviceList = arr
    }
    @action.bound
    initializeWebSocket(socketURL: string) {
        const { sendMessage, messages, isConnected } = useWebSocket(socketURL);
        this.isConnected = isConnected;
        this.sendMessage = sendMessage;
        this.messages = messages;
    }

    @action.bound
    handleMessages(messages: any) {
        switch (messages?.cmd) {
            case 'dev_sleep':
                this.sleep = messages;
                break;
            case "online_status":
                this.device_online = messages.status || 0
                if (messages.status == 0 && deviceStore.remoteInfo.type == 'remote') {
                    deviceStore.cleanStatus() // 清除远程相关状态
                    this.linkSubDeviceSn = ''
                }
                break;
            case 'version':
                this.firmware_version = messages.firmware_version
                break;
            case 'ota_progress_bar':
                this.progress = messages.percent
                break;
            case 'volume':
                this.volume = messages.data
                break;
            case 'auto_answer':
                this.callRoleStatus = messages.data
            case "co_interval":
                this.coInterval = messages.data
                break;
            case "typeC_connected_device_current":
                this.typeDeviceConnect = messages.type
                break;
            case 'fingerClip_RT_upload':
                this.fingerInfo = messages
                break;
            case 'ble_link':
                this.linkSubDeviceStatus = messages.status;
                if (messages.status == 0) {
                    deviceStore.cleanStatus() // 清除远程相关状态
                    this.linkSubDeviceSn = ''
                } else {
                    this.linkSubDeviceSn = messages.sn_id
                    deviceStore.sendBleWrite(deviceStore.remoteInfo)
                    Toast.show({ content: "连接激光治疗仪成功" })
                }
                break;
            case 'call':
                if (!this.inComingVisible && !this.isHandlingCall) {
                    this.inComingCall = messages;
                    this.openInComingModal();
                }
                break;
            case 'exit_rtc':
                this.hideInComingModal()
                break;
            case 'ble_rssi':
                const { rssi, sn_id } = messages;
                this.bleRssiMap.set(sn_id, { rssi, sn_id });
                this.subDevices = this.subDevices.map(item => {
                    const newRssiData = this.bleRssiMap.get(item.device_sn);
                    return {
                        ...item,
                        device_rssi: newRssiData ? newRssiData.rssi : item.device_rssi ?? null,
                    };
                });
                break;
            default:
                break;
        }
    }

    sendMessage = (message: any) => {
        console.warn('WebSocket is not connected.');
    }
    openInComingModal() {
        this.inComingVisible = true
    };
    hideInComingModal() {
        this.inComingVisible = false;
        this.isHandlingCall = false
        this.inComingCall = {} as InComingCall
    }
}


const webSocketStore = new WebSocketStore();
export default webSocketStore;